import 'dart:async';
import 'dart:ui';
import 'package:eh_mobile/common/utils/extension.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';

import '../../../../common/values/svg_image.dart';

// 弹出灯光选择模式
class SelectModeOverlay {
  // final List modelList;
  // final Function selectModeOverlayCallBack;
  late OverlayEntry _overlayFloat;

  SelectModeOverlay.show(
    BuildContext context, List modelList, {
    required Function selectModeOverlayCallBack,
  }) {
    _overlayFloat = OverlayEntry(
      builder: (context) => SelectModeWidget(
        selectModeOverlayCallBack: (value,name) {
          selectModeOverlayCallBack(value,name);
        },
        closeOverlyCallback: () => closeOverlayView(),
        modelList: modelList,
      ),
    );
    Overlay.of(context).insert(_overlayFloat);
  }

  SelectModeOverlay.hidden() {
    closeOverlayView();
  }

  void closeOverlayView() {
    _overlayFloat.remove();
  }
}

class SelectModeWidget extends StatefulWidget {
  const SelectModeWidget({
    super.key,
    required this.selectModeOverlayCallBack,
    required this.closeOverlyCallback,
    required this.modelList,
  });
  final List modelList;

  final Function selectModeOverlayCallBack;
  final VoidCallback closeOverlyCallback;

  @override
  State<SelectModeWidget> createState() => _SelectModeWidgetyState();
}

class _SelectModeWidgetyState extends State<SelectModeWidget>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  late double _popWidgetHeight;

  bool _showPopView = false;
  int _currentIndex = 0;
  @override
  void initState() {
    int row = ((widget.modelList.length % 4 > 0)
            ? (widget.modelList.length / 4 + 1).toInt()
            : widget.modelList.length / 4)
        .toInt();
    _popWidgetHeight = 68.r + row * 48.r + 14.r + ScreenUtil().bottomBarHeight;
    double maxLowHeight =328.h;
    _popWidgetHeight= _popWidgetHeight<maxLowHeight?maxLowHeight:_popWidgetHeight;
    //延迟执行
    _delayAnimation();
    // 初始化
    super.initState();
  }

  // 延迟动画执行
  void _delayAnimation() async {
    await Future.delayed(const Duration(milliseconds: 1));
    _showPopView = true;
    setState(() {});
  }

  // 关闭按钮点击事件
  void _closeButtonClick() async {
    if (!_showPopView) {
      return;
    }
    _showPopView = false;
    setState(() {});
    await Future.delayed(const Duration(milliseconds: 300));
    widget.closeOverlyCallback();
  }

  // 构建弹出widget
  Widget _buildPopWidget() {
    return Stack(
      children: [
        ClipRRect(
            borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(24), topRight: Radius.circular(24)),
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 50, sigmaY: 50),
              child: Container(
                decoration: BoxDecoration(
                    color: const Color.fromRGBO(28, 28, 28, 0.25),
                    borderRadius: const BorderRadius.only(
                        topLeft: Radius.circular(24),
                        topRight: Radius.circular(24)),
                    border: Border.all(
                        width: 1,
                        color: const Color.fromRGBO(255, 255, 255, 0.08))),
                width: MediaQuery.of(context).size.width,
                height: _popWidgetHeight,
                child: Stack(
                  children: [
                    Positioned(
                        left: 25.r,
                        top: 12.r,
                        child: Text(
                          '选择模式',
                          style: 18.ts,
                        )),
                    Positioned(
                        top: 8.r,
                        right: 10.r,
                        child: Container(
                          width: 42.r,
                          height: 32.r,
                          padding: const EdgeInsets.fromLTRB(0, 4, 0, 4).r,
                          decoration: BoxDecoration(
                            color: const Color.fromRGBO(222, 222, 222, 0.1),
                            borderRadius: BorderRadius.circular(16.r),
                          ),
                          child: SvgPicture.asset(
                            SVGImage.icCloseSSvg,
                            color: Colors.white,
                          ),
                        ).onClick(() {
                          _closeButtonClick();
                        })),
                    Positioned(
                        top: 55.r,
                        child: Container(
                          width: 1.sw,
                          height: 1,
                          color: const Color.fromRGBO(255, 255, 255, 0.08),
                        )),
                    Positioned(
                      top: 68.r,
                      child: SizedBox(
                          height: _popWidgetHeight - 68.r,
                          width: 1.sw,
                          child: GridView.builder(
                            padding:
                                const EdgeInsets.only(left: 25, right: 25).r,
                            scrollDirection: Axis.vertical,
                            itemCount: widget.modelList.length,
                            physics:
                                const NeverScrollableScrollPhysics(), // 不滑动
                            gridDelegate:
                                SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 4, // 主轴上Item长度
                              mainAxisSpacing: 12.r, // 主轴item之间的间距
                              crossAxisSpacing: 12.r, // 水平item之间的间距
                              childAspectRatio: 76 / 36.0, //宽高比
                              mainAxisExtent: 36.0.r,
                            ),
                            itemBuilder: (context, index) {
                              String itemName =widget.modelList[index];
                              return Container(
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  color: _currentIndex == index
                                      ? const Color.fromRGBO(255, 255, 255, 0.9)
                                      : const Color.fromRGBO(
                                          222, 222, 222, 0.1),
                                  borderRadius: BorderRadius.circular(9).r,
                                ),
                                child: Text(
                                  itemName,
                                  style: 16.ts.copyWith(
                                      color: _currentIndex == index
                                          ? const Color.fromRGBO(50, 50, 50, 1)
                                          : const Color.fromRGBO(
                                              222, 222, 222, 1)),
                                ),
                              ).onClick(() {
                                setState(() {
                                  _currentIndex = index;
                                  widget
                                      .selectModeOverlayCallBack(_currentIndex,itemName);
                                  _closeButtonClick();

                                });
                              });
                            },
                          )),
                    )
                  ],
                ),
              ),
            ))
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Positioned.fill(
      child: Material(
          color: Colors.transparent,
          child: Stack(
            children: [
              GestureDetector(
                onTap: _closeButtonClick,
                child: Container(
                  color: Colors.transparent,
                  width: MediaQuery.of(context).size.width,
                  height: MediaQuery.of(context).size.height,
                ),
              ),
              AnimatedPositioned(
                  top: _showPopView
                      ? MediaQuery.of(context).size.height - _popWidgetHeight
                      : MediaQuery.of(context).size.height,
                  duration: const Duration(milliseconds: 300),
                  curve: Curves.easeInOut,
                  child: _buildPopWidget())
            ],
          )),
    );
  }

  @override
  void dispose() {
    // 销毁
    super.dispose();
  }
}
